<?php


namespace Beerus\Modules\Album\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\cache\album\AlbumRecommendCache;
use Doraemon\service\User;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class AlbumUserWhiteListController extends Controller
{
    const PAGE_SIZE = 20;

    public function index(Request $request, Content $content)
    {
        // 处理查询条件
        $uidArr = array_filter(explode(',', AlbumRecommendCache::getUserWhitelist()));
        $list = [];
        if ($uidArr) {
            $userInfo = [];
            foreach ($uidArr as $uid) {
                $userInfo['uid'] = $uid;
                $list[] = $userInfo;
            }
        }
        $total = count($list);
        $gridModel = new pGridDataModel($list, $total, ['perPage' => self::PAGE_SIZE]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->tools(function ($tool) {
                $url = "/admin/album/whitelist/create";
                $tool->append('<a class="btn btn-warning" href="javascript:layer.open({
                                type: 2,
                                title: \'更新用户白名单\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'1000px\', \'600px\'],
                                content: \''.$url.'\'
                            });
               ">更新用户白名单</a>');
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->expand();//默认展开
            });
            $grid->column('uid', '用户信息')->userBasicInfo();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableActions();

        });

        return $content->header("发现好物 | 用户白名单")->row($grid);

    }

    public function create(Request $request, \App\Admin\Extensions\WorkContent $content)
    {

        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 20);
SCRIPT;
            Admin::script($script);
        }
        $info['user_list'] = AlbumRecommendCache::getUserWhitelist();
        $form = new Form($info);
        $form->hidden('id');
        $form->textarea('user_list', '用户白名单')->rows(15)->setWidth(40, 0)->placeholder('请输入用户uid,并使用逗号分隔');
        $form->confirm('确定更新吗？', 'add');
        $form->action(route('album_whitelist.save'));
        $title = '更新用户白名单';

        return $content->header($title)
            ->row($form);
    }

    public function save(Request $request)
    {
        $userList = $request->input('user_list');
        try {
            //过滤回车和换行
            $userList = preg_replace('/\r|\n/', '', $userList);
            //过滤空格
            $userList = str_replace(' ', '', $userList);
            $uidArr = array_unique(array_filter(explode(',', $userList)));
            $userInfoMap = User::getBatchBasicUserInfo($uidArr);
            $userInfoMap = array_column($userInfoMap, null, 'uid');
            foreach ($uidArr as $uid) {
                $nickName = $userInfoMap[$uid] ?? '';
                if (!$nickName) {
                    throw new \Exception('uid:'."$uid".'该用户不存在');
                }
            }
            AlbumRecommendCache::addUserWhitelist(implode(',', $uidArr));

            $success = new MessageBag([
                'title' => '保存成功',
            ]);

            return redirect('/admin/album/whitelist/create?code=1')->with(compact('success'));

        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败,'.$e->getMessage(),
            ]);

            return back()->withInput()->with(compact('error'));
        }
    }

}